package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerConnection {
	
	public static Socket connectionSocket;
	public static ServerSocket serverSocket; 
	
	/**
	 * Open Receiver connection
	 * @param port
	 * @throws Exception
	 */
	public static boolean openListeningConnection(int port){
		boolean ret = true;
		
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			ret = false;
		}
		
		return ret;
	}
	
	/**
	 * 
	 * @param port
	 * @return
	 * @throws Exception
	 */
	public static String receive(){
      String message = null;
	  try
	  {
          connectionSocket = serverSocket.accept();
          BufferedReader receiveObject = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));		          
          message = receiveObject.readLine();
      }
	  catch (IOException e) {
		  System.out.println("Connection error (Client crash?)");
	  }
	  return message;
	}
	
	
	public static void send(String message){
		PrintWriter sendObject = null;
		
		try {
			sendObject = new PrintWriter(connectionSocket.getOutputStream(), true);
			sendObject.println(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void send(String message, Socket soc){
		PrintWriter sendObject = null;
		
		try {
			sendObject = new PrintWriter(soc.getOutputStream(), true);
			sendObject.println(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void sendGameState(Server s){
		OutputStream os;
		try {
			os = connectionSocket.getOutputStream();
			ObjectOutputStream sendObject = new ObjectOutputStream(os);
			sendObject.writeObject(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void closeConnection(){
		try {
			connectionSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void closeListeningConnection(){
		try {
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
